<?php

require './vendor/autoload.php';

Restart:

$pid = pcntl_fork();

function recursiveReadDir($dir, $parentDir = '')
{
    static $finalDir = [];

    $finalDir[] = $dir;

    $parentDir = $parentDir == '' ? $dir : $parentDir;

    if (is_dir($dir)) {
        $handle = opendir($dir);

        while (false !== ($entry = readdir($handle))) {

            if ($entry != '.' && $entry != '..') {
                $relativePath = $dir . '/' . $entry;
                if (is_dir($relativePath)) {
                    recursiveReadDir($relativePath, $dir);
                }
            }

        }
    } else {
        $finalDir[] = $parentDir;
    }

    return $finalDir;
}

if ($pid > 0) {
    $fd = inotify_init();

    foreach (recursiveReadDir('./') as $dir) {
        inotify_add_watch($fd, $dir, IN_MODIFY);
    }

    $events = inotify_read($fd);

    posix_kill($pid, SIGTERM);

    fclose($fd);

    pcntl_wait($status);

    goto Restart;
} elseif ($pid == 0) {

    /** @var \DI\Container $container */
    $container = require './bootstrap/app.php';

    /** @var \Asf\Foundation\Server $server */
    $server = $container->make(
        \Asf\Foundation\Server::class,
        [
            'address' => my_env('ADDRESS', '0.0.0.0'),
            'port' => my_env('PORT', '9502')
        ]
    );

    \Asf\Database\ConnectionResolver::$container = \Asf\Routing\Route::$container = \Asf\Foundation\Http\Kernel::$container = $container;

    \Asf\Foundation\Http\Kernel::staticBootstrap();

    require APP_PATH . '/route/web.php';

    $server->on('WorkerStart', function($server, $workerId) {
        \Asf\Foundation\Http\Kernel::initDatabase();
    });

    $server->handleRequest(function($request, $response) use ($container) {
        \Asf\Util\Context::set('container', $container);

        $kernel = $container->make(
            \Asf\Foundation\Http\Kernel::class
        );

        /** @var \Asf\Contracts\Http\Response $kernelResponse */
        $kernelResponse = $kernel->handle(
            $request = \Asf\Http\Request::createFromSwooleRequest($request)
        );

        $content = $kernelResponse->makeupSwooleResponse($response);

        $response->end($content);

    });

    $server->run();
} else {
    exit(0);
}